package com.leaves.core.validation.date;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author Chenweiwei
 * @Date 2021/11/9 19:58
 * @Version 1.0
 */
public class SelfDateValueValidator implements ConstraintValidator<SelfDateValue, String> {

    private String dateFormat;


    @Override
    public void initialize(SelfDateValue constraintAnnotation) {
        dateFormat = constraintAnnotation.dateFormat();
    }

    @Override
    public boolean isValid(String dateValue, ConstraintValidatorContext constraintValidatorContext) {
        //为空则放过，因为在此校验之前会加入@NotNull或@NotBlank校验
        if (ObjectUtil.isEmpty(dateValue)) {
            return true;
        }
        if (dateValue.length() != dateFormat.length()) {
            return false;
        }
        try {
            DateUtil.parse(dateValue, dateFormat);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
